package com.taiji.web.controller.workOrder;

import com.alibaba.fastjson2.JSONObject;
import com.taiji.workOrder.domain.MessageBody;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.EOFException;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author a22999
 * @since 2023/06/30 15:03
 * description:
 */
@Component
@ServerEndpoint("/websocket/message/{username}")
public class WebSocketServer {


    /**
     * 根据name存储的Socket会话Map
     * key:username, value:session
     */
    public static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 根据Socket会话ID存储的username的Map
     * key:sessionId, value:username
     */
    public static ConcurrentHashMap<String, String> nameMap = new ConcurrentHashMap<>();


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("username") String username) throws Exception
    {
        System.out.println(username);
        sessionMap.put(username, session);
        nameMap.put(session.getId(),username);
    /*    MessageBody messageBody = new MessageBody();
        messageBody.setFromName("系统");
        messageBody.setToName(username);
        messageBody.setSendTime(new Date());
        messageBody.setContent("您已连接ITSM项目管理系统");
        session.getBasicRemote().sendText(JSONObject.toJSONString(messageBody));*/
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session)
    {
        String name = nameMap.remove(session.getId());
        sessionMap.remove(name);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException
    {
        MessageBody messageBody = JSONObject.parseObject(message, MessageBody.class);
        if (messageBody == null){
            return;
        }
        String fromUser = nameMap.get(session.getId());
        //设置发消息的人
        messageBody.setFromName(fromUser);
        //设置发送时间
        messageBody.setSendTime(new Date());

        //将消息转发给收消息的人
        Session toSession = sessionMap.get(messageBody.getToName());

        if (toSession != null){
            toSession.getBasicRemote().sendText(JSONObject.toJSONString(messageBody));
        }else {
            MessageBody systemMessage = new MessageBody();
            systemMessage.setContent( "业务员不在线，发送失败");
            systemMessage.setFromName("提示");
            session.getBasicRemote().sendText(JSONObject.toJSONString(systemMessage));
        }
    }


    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception
    {
        if (exception instanceof EOFException && exception.getMessage() == null){
            String name = nameMap.get(session.getId());
            nameMap.remove(session.getId());
            sessionMap.remove(name);
        }
    }



    /**
     * 单发消息
     */
    public static boolean sendMessageToUser(MessageBody message) throws IOException {
        System.out.println(message.getToName());
        System.out.println(sessionMap);
        Session session = sessionMap.get(message.getToName());
        if (session!=null) {
            session.getBasicRemote().sendText(JSONObject.toJSONString(message));
            return true;
        } else {
            System.out.println("请求的 用户:不在该服务器上");
            //消息接受方不在线  把消息存储到数据库
            return false;
        }
    }


}
